﻿using System.Security.Claims;
using AutoMapper;
using BlogSystem.Common.Config.DI.annotation;
using BlogSystem.Data.Entity;
using BlogSystem.Data.Repository.RepositoryImpl;
using BlogSystem.Exception;
using BlogSystem.Model.Request;
using BlogSystem.Model.Respones;

namespace BlogSystem.Service.Impl;

[Ioc("scoped")]
public class RemarkServiceIMpl : IRemarkService
{

    private readonly IMapper _mapper;
    
    private readonly IHttpContextAccessor _httpContextAccessor;

    private readonly RemarkRepository _remarkRepository;
    
    public RemarkServiceIMpl(IMapper mapper,IHttpContextAccessor httpContextAccessor,RemarkRepository remarkRepository)
    {
        _mapper = mapper;
        _httpContextAccessor = httpContextAccessor;
        _remarkRepository = remarkRepository;
    }
    

    /// <summary>
    /// 分页+查询
    /// </summary>
    /// <param name="keyWord">关键词</param>
    /// <param name="pageIndex">页码</param>
    /// <param name="pageSize">页面大小</param>
    /// <returns></returns>
    public async Task<IQueryable<RemarkResponse>> GetRemarksAsync(string keyWord, int pageIndex, int pageSize)
    {
        return await _remarkRepository.GetAllByPage(keyWord, pageIndex, pageSize);

    }
    
    /**
     * 添加
     */
    public async Task<bool> AddRemark(RemarkRequest remarkRequest)
    {
        // 获取到用户的信息
        var user = _httpContextAccessor.HttpContext?.User;
        var userid = user.FindFirstValue("id");
        
        var remark = _mapper.Map<Remark>(remarkRequest);
        remark.UserId = int.Parse(userid);
        
        return await _remarkRepository.Add(remark);
    }
    
    public async Task<bool> UpdateRemark(int id,RemarkRequest remarkRequest)
    {
        //获取id,查找出对应的数据库Article
        var remark = await _remarkRepository.GetById(id);
        if (remark==null)
            throw new BusinessException("信息不匹配，无法修改");
        
        var res = await _remarkRepository.Update( _mapper.Map(remarkRequest,remark));
        return res;
    }


    /**
     * 逻辑删除评论
     */
    public async Task<bool> DelRemarkById(int id)
    {
        var res = await _remarkRepository.DelRemarkById(id);
        return res;
    }

    /**
     * 根据评论id获取评论
     */
    public async Task<Remark> GetById(int id)
    {
        var remark = await _remarkRepository.GetById(id);
        if (remark.Status!=1)
        {
            throw new BusinessException("该评论已被屏蔽。");
        }
        return remark;
      
    }

    /**
     * 根据文章id获取评论信息
     */
    public async Task<List<Remark>> GetByArticleId(int articleId)
    {
        List<Remark> remarks =await _remarkRepository.GetByArticleId(articleId);
        
       // IQueryable<Remark> remarks = _context.RemarksParameter.Where( c =>c.ArticleId==articleId && c.Status==1).ToList();
        return remarks;
    }
    
}